package com.yunyao.framework.service.impl;

import com.alibaba.fastjson2.util.DateUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunyao.common.constant.enums.ContractPriceType;
import com.yunyao.common.constant.enums.DataDeletedStatus;
import com.yunyao.common.constant.enums.DateFormatPattern;
import com.yunyao.common.constant.enums.ProjectSettlementStatusEnum;
import com.yunyao.common.constant.enums.ReconciliationStatusEnum;
import com.yunyao.common.core.BaseContext;
import com.yunyao.common.core.UserInfoRequest;
import com.yunyao.common.dto.excel.SettlementExcelDto;
import com.yunyao.common.dto.project.HistoryQtDto;
import com.yunyao.common.dto.supplier.SupplierSettlementDto;
import com.yunyao.common.dto.supplier.SupplierSettlementMaterialDto;
import com.yunyao.common.dto.supplier.SupplierSettlementOrderDto;
import com.yunyao.common.exception.BusinessException;
import com.yunyao.common.web.enums.ResultMsgEnum;
import com.yunyao.common.web.util.ConvertUtil;
import com.yunyao.common.web.util.PageResult;
import com.yunyao.common.web.util.YResult;
import com.yunyao.dao.model.*;
import com.yunyao.dao.service.bamu.*;
import com.yunyao.framework.audit.SupplierSettlementAuditHandle;
import com.yunyao.framework.dto.spreconciliatioin.SpReconciliationMaterialDto;
import com.yunyao.framework.dto.supplier.*;
import com.yunyao.framework.service.SupplierSettlementPayNodeService;
import com.yunyao.framework.service.SupplierSettlementService;
import com.yunyao.framework.vo.spreconciliation.SpReconciliationMaterialVO;
import com.yunyao.framework.vo.supplier.SupplierSettlementInfoVO;
import com.yunyao.framework.vo.supplier.SupplierSettlementMaterialVO;
import com.yunyao.framework.vo.supplier.SupplierSettlementOrderVO;
import com.yunyao.framework.vo.supplier.SupplierSettlementVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author xingjishuai
 * @date 2024-07-29
 */
@Slf4j
@Service
public class SupplierSettlementServiceImpl implements SupplierSettlementService {
    @Autowired
    private IBamuSpReconciliationSettlementPayNodeService iBamuSpReconciliationSettlementPayNodeService;
    @Autowired
    private SupplierSettlementPayNodeService iBamuSupplierSettlementPayNodeService;
    @Autowired
    private IBamuPurchaseContractService iBamuPurchaseContractService;
    @Autowired
    private SupplierSettlementAuditHandle supplierSettlementAuditHandle;
    @Autowired
    private IBamuSpReconciliationService iBamuSpReconciliationService;
    @Autowired
    private IBamuSpReconciliationOrderMaterialService iBamuSpReconciliationOrderMaterialService;
    @Autowired
    private IBamuAuditConfirmHistoryService iBamuAuditConfirmHistoryService;
    @Autowired
    private IBamuContractWirePayService iBamuContractWirePayService;
    @Autowired
    private IBamuSpReconciliationSettlementService iBamuSpReconciliationSettlementService;
    @Autowired
    private IBamuSpReconciliationSettlementOrderService iBamuSpReconciliationSettlementOrderService;
    @Autowired
    private IBamuSpReconciliationSettlementOrderMaterialService iBamuSpReconciliationSettlementOrderMaterialService;

    @Override
    public YResult<PageResult<SupplierSettlementVO>> pageList(SupplierSettlementDto supplierSettlementDto) {
        // 构建查询条件
        LambdaQueryWrapper<BamuSpReconciliationSettlement> queryWrapper =
                new LambdaQueryWrapper<BamuSpReconciliationSettlement>()
                        .like(StringUtils.isNotBlank(supplierSettlementDto.getContractNo()), BamuSpReconciliationSettlement::getContractNo, supplierSettlementDto.getContractNo())
                        .eq(BamuSpReconciliationSettlement::getIsDeleted,
                                DataDeletedStatus.NO.getType())
                        .between(StringUtils.isNotBlank(supplierSettlementDto.getSettlementStartDate()) && StringUtils.isNotBlank(supplierSettlementDto.getSettlementEndDate()),
                                BamuSpReconciliationSettlement::getSettlementDate,
                                ConvertUtil.getStartOfDay(ConvertUtil.getString2Date(supplierSettlementDto.getSettlementStartDate())),
                                ConvertUtil.getEndOfDay(ConvertUtil.getString2Date(supplierSettlementDto.getSettlementEndDate())))
                        .eq(StringUtils.isNotBlank(supplierSettlementDto.getContractId()),
                                BamuSpReconciliationSettlement::getContractId,
                                supplierSettlementDto.getContractId())
                        .eq(StringUtils.isNotBlank(supplierSettlementDto.getContractMethod()),
                                BamuSpReconciliationSettlement::getContractMethod,
                                supplierSettlementDto.getContractMethod())
                        .like(StringUtils.isNotBlank(supplierSettlementDto.getContractName()),
                                BamuSpReconciliationSettlement::getContractName,
                                supplierSettlementDto.getContractName())
                        .eq(StringUtils.isNotBlank(supplierSettlementDto.getProjectId()),
                                BamuSpReconciliationSettlement::getProjectId,
                                supplierSettlementDto.getProjectId())
                        .like(StringUtils.isNotBlank(supplierSettlementDto.getProjectName()),
                                BamuSpReconciliationSettlement::getProjectName,
                                supplierSettlementDto.getProjectName())
                        .like(StringUtils.isNotBlank(supplierSettlementDto.getSupplierDeptName()),
                                BamuSpReconciliationSettlement::getSupplierDeptName,
                                supplierSettlementDto.getSupplierDeptName())
                        .in(CollectionUtils.isNotEmpty(BaseContext.getProjectList()), BamuSpReconciliationSettlement::getProjectId, BaseContext.getProjectList())
                        .in(CollectionUtils.isNotEmpty(BaseContext.getSupplierList()),
                                BamuSpReconciliationSettlement::getSupplierDeptId,
                                BaseContext.getSupplierList()).orderByDesc(BamuSpReconciliationSettlement::getId);


        // 分页查询
        IPage<BamuSpReconciliationSettlement> settlementPage =
                new Page<>(supplierSettlementDto.getPageIndex(),
                        supplierSettlementDto.getPageSize());
        settlementPage = iBamuSpReconciliationSettlementService.page(settlementPage, queryWrapper);

        // 处理查询结果
        if (CollectionUtils.isEmpty(settlementPage.getRecords())) {
            return YResult.success(new PageResult<>());
        }

        // 转换为VO对象列表
        List<SupplierSettlementVO> voList = daoToVoList(settlementPage.getRecords());

        // 返回分页结果
        return YResult.success(new PageResult<>(voList, settlementPage.getCurrent(),
                settlementPage.getSize(), settlementPage.getPages(), settlementPage.getTotal()));
    }

    private List<SupplierSettlementVO> daoToVoList(List<BamuSpReconciliationSettlement> records) {
        List<String> contractIdList =
                records.stream().map(BamuSpReconciliationSettlement::getContractId).distinct().toList();
        Map<String, BamuContractWirePay> contractWirePayMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(contractIdList)) {
            contractWirePayMap.putAll(iBamuContractWirePayService.mapByContractIdList(contractIdList));
        }
        return records.stream().map(x -> daoToVo(x, contractWirePayMap)).collect(Collectors.toList());
    }

    /**
     * 将数据访问对象（DAO）层的数据转换为视图对象（VO）
     * 该方法主要用于供应商结算数据的转换，以便在不同层面上使用
     *
     * @param bamuSpReconciliationSettlement 供应商结算数据对象，包含详细的结算信息
     * @param contractWirePayMap             合约与支付方式的映射，用于补充结算数据中的合约支付方式信息
     * @return 返回转换后的 SupplierSettlementVO 对象，该对象包含了转换后的供应商结算信息
     */
    private SupplierSettlementVO daoToVo(BamuSpReconciliationSettlement bamuSpReconciliationSettlement, Map<String, BamuContractWirePay> contractWirePayMap) {
        // 初始化供应商结算视图对象
        SupplierSettlementVO vo = new SupplierSettlementVO();
        // 将结算数据对象的基本属性复制到视图对象中
        BeanUtils.copyProperties(bamuSpReconciliationSettlement, vo);
        // 从合约支付方式映射中获取与当前结算数据相关的合约支付方式
        BamuContractWirePay contractWirePay = contractWirePayMap.get(bamuSpReconciliationSettlement.getContractId());
        // 如果合约支付方式存在，则将其类型设置到视图对象中
        if (Objects.nonNull(contractWirePay)) {
            vo.setPriceType(contractWirePay.getPriceType());
            vo.setPriceTypeDesc(ContractPriceType.typeOfDesc(Integer.valueOf(contractWirePay.getPriceType())));
            vo.setPaymentCycle(contractWirePay.getPaymentCycle());
        }
        // 返回转换后的视图对象
        return vo;
    }

    @Override
    public YResult<PageResult<SupplierSettlementMaterialVO>> materialPageList(SupplierSettlementMaterialDto supplierSettlementMaterialDto) {
        LambdaQueryWrapper<BamuSpReconciliationSettlementOrderMaterial> queryWrapper =
                new LambdaQueryWrapper<BamuSpReconciliationSettlementOrderMaterial>()
                        .eq(BamuSpReconciliationSettlementOrderMaterial::getIsDeleted,
                                DataDeletedStatus.NO.getType())
                        .eq(BamuSpReconciliationSettlementOrderMaterial::getReconciliationSettlementId,
                                supplierSettlementMaterialDto.getReconciliationSettlementId())
                        .orderByAsc(BamuSpReconciliationSettlementOrderMaterial::getMaterialSortNum);
        // 分页查询
        IPage<BamuSpReconciliationSettlementOrderMaterial> settlementPage =
                new Page<>(supplierSettlementMaterialDto.getPageIndex(),
                        supplierSettlementMaterialDto.getPageSize());
        settlementPage = iBamuSpReconciliationSettlementOrderMaterialService.page(settlementPage,
                queryWrapper);

        // 处理查询结果
        if (CollectionUtils.isEmpty(settlementPage.getRecords())) {
            return YResult.success(new PageResult<>());
        }

        // 转换为VO对象列表
        List<SupplierSettlementMaterialVO> voList =
                materialDaoToVoList(settlementPage.getRecords());

        // 返回分页结果
        return YResult.success(new PageResult<>(voList, settlementPage.getCurrent(),
                settlementPage.getSize(), settlementPage.getPages(), settlementPage.getTotal()));
    }

    @Override
    public YResult<PageResult<SpReconciliationMaterialVO>> getSpReconciliationMaterialListbySupplyId(SpReconciliationMaterialDto spReconciliationMaterialDto) {
        LambdaQueryWrapper<BamuSpReconciliationOrderMaterial> wrapper = new LambdaQueryWrapper<BamuSpReconciliationOrderMaterial>()
                .in(BamuSpReconciliationOrderMaterial::getReconciliationId, spReconciliationMaterialDto.getIdList()) // 使用in方法查询ID列表中的任意一个
//                .eq(BamuSoSupplyMaterial::getPurchaseApplyId, purchaseApplyId)
                .eq(BamuSpReconciliationOrderMaterial::getIsDeleted, DataDeletedStatus.NO.getType());
        // 分页查询
        IPage<BamuSpReconciliationOrderMaterial> payPage = new Page<>(spReconciliationMaterialDto.getPageIndex(), spReconciliationMaterialDto.getPageSize());
        payPage = iBamuSpReconciliationOrderMaterialService.page(payPage, wrapper);

        // 处理查询结果
        if (CollectionUtils.isEmpty(payPage.getRecords())) {
            return YResult.success(new PageResult<>());
        }

        // 转换为VO对象列表
        List<SpReconciliationMaterialVO> materialVOList = materialDaoToVoList1(payPage.getRecords());

        // 返回分页结果
        return YResult.success(new PageResult<>(materialVOList, payPage.getCurrent(), payPage.getSize(), payPage.getPages(), payPage.getTotal()));

    }

    private List<SpReconciliationMaterialVO> materialDaoToVoList1(List<BamuSpReconciliationOrderMaterial> records) {
        return records.stream().map(this::materialDaoToVo1).collect(Collectors.toList());
    }

    private SpReconciliationMaterialVO materialDaoToVo1(BamuSpReconciliationOrderMaterial bamuSpReconciliationOrderMaterial) {
        SpReconciliationMaterialVO spReconciliationMaterialVO = new SpReconciliationMaterialVO();
        BeanUtils.copyProperties(bamuSpReconciliationOrderMaterial, spReconciliationMaterialVO);
        return spReconciliationMaterialVO;
    }

    private List<SupplierSettlementMaterialVO> materialDaoToVoList(List<BamuSpReconciliationSettlementOrderMaterial> records) {
        return records.stream().map(this::materialDaoToVo).collect(Collectors.toList());
    }

    private SupplierSettlementMaterialVO materialDaoToVo(BamuSpReconciliationSettlementOrderMaterial bamuSpReconciliationSettlementOrderMaterial) {
        SupplierSettlementMaterialVO vo = new SupplierSettlementMaterialVO();
        BeanUtils.copyProperties(bamuSpReconciliationSettlementOrderMaterial, vo);
        return vo;
    }

    /**
     * 根据供应商结算ID获取结算信息
     * 此方法通过查询数据库中未被删除且ID匹配的结算记录来获取供应商的结算信息
     *
     * @param settlementDto 包含结算ID的请求对象
     * @return 包含供应商结算信息的结果对象，如果查询不到对应的数据则返回错误结果
     */
    @Override
    public YResult<SupplierSettlementInfoVO> getInfo(SupplierSettlementDto settlementDto) {
        // 创建查询条件，用于筛选未被删除且ID匹配的结算记录
        LambdaQueryWrapper<BamuSpReconciliationSettlement> queryWrapper =
                new LambdaQueryWrapper<BamuSpReconciliationSettlement>()
                        .eq(BamuSpReconciliationSettlement::getIsDeleted,
                                DataDeletedStatus.NO.getType()).eq(BamuSpReconciliationSettlement::getId, settlementDto.getId());

        // 使用查询条件获取第一个匹配的结算记录
        BamuSpReconciliationSettlement bamuSpReconciliationSettlement =
                iBamuSpReconciliationSettlementService.getOne(queryWrapper);

        // 如果结算记录为空，返回错误结果，表示没有数据
        if (Objects.isNull(bamuSpReconciliationSettlement)) {
            return YResult.error(ResultMsgEnum.NO_DATA);
        }

        // 将获取到的结算记录转换为供应商结算信息VO，并返回成功结果
        return YResult.success(daoToInfoVo(bamuSpReconciliationSettlement, settlementDto.getContractMethod()));
    }

    private SupplierSettlementInfoVO daoToInfoVo(BamuSpReconciliationSettlement bamuSpReconciliationSettlement, String contractMethod) {
        SupplierSettlementInfoVO infoVO = new SupplierSettlementInfoVO();
        BeanUtils.copyProperties(bamuSpReconciliationSettlement, infoVO);

        List<BamuSpReconciliationSettlementPayNode> payNodes = iBamuSpReconciliationSettlementPayNodeService.lambdaQuery()
                .eq(BamuSpReconciliationSettlementPayNode::getOrderId, bamuSpReconciliationSettlement.getOrderId())
                .eq(BamuSpReconciliationSettlementPayNode::getContractId, bamuSpReconciliationSettlement.getContractId())
                .eq(BamuSpReconciliationSettlementPayNode::getContractMethod, contractMethod)
                .eq(BamuSpReconciliationSettlementPayNode::getIsDeleted, 0)
                .list();

        infoVO.setReconciliationSettlementPayNodes(payNodes);
        //获取合同id
        String contractId = bamuSpReconciliationSettlement.getContractId();
        //根据合同id，获取小于当前结算单时间的历史结算单
        List<BamuSpReconciliationSettlement> list = iBamuSpReconciliationSettlementService.lambdaQuery()
                .eq(BamuSpReconciliationSettlement::getContractId, contractId)
                .lt(BamuSpReconciliationSettlement::getCreatedAt,bamuSpReconciliationSettlement.getCreatedAt())
                .eq(BamuSpReconciliationSettlement::getIsDeleted, DataDeletedStatus.NO.getType()).list();
        if(CollectionUtils.isNotEmpty(list)){
            List<String> settlementIdList = list.stream().map(BamuSpReconciliationSettlement::getId).distinct().toList();
            //查询材料表，获取所有结算单的历史结算金额
            List<BamuSpReconciliationSettlementOrderMaterial> resultList = iBamuSpReconciliationSettlementOrderMaterialService.lambdaQuery()
                    .in(BamuSpReconciliationSettlementOrderMaterial::getReconciliationSettlementId, settlementIdList)
                    .list();
            if(CollectionUtils.isNotEmpty(resultList)){
                BigDecimal sum = resultList.stream().map(BamuSpReconciliationSettlementOrderMaterial::getReconciliationPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
                infoVO.setHistorySettlementAmount(sum);
            }
        }
        return infoVO;
    }

    /**
     * 确认供应商结算单
     *
     * @param supplierSettlementConfirmDto 供应商结算确认数据传输对象，包含确认所需的各项信息
     * @return 返回一个泛型为String的YResult对象，包含操作结果或错误信息
     */
    @Override
    public YResult<String> confirm(SupplierSettlementConfirmDto supplierSettlementConfirmDto) {
        // 提取供应商结算单ID
        String id = supplierSettlementConfirmDto.getId();
        // 提取确认对账文件路径
        String confirmReconciliationFile =
                supplierSettlementConfirmDto.getConfirmReconciliationFile();
        //供应商确认附件要求必传
        if (StringUtils.isBlank(confirmReconciliationFile)) {
            return YResult.error(ResultMsgEnum.IMPORT_FILE_ISNULL);
        }
        // 提取确认对账备注
        String confirmReconciliationMark =
                supplierSettlementConfirmDto.getConfirmReconciliationMark();
        boolean isConfirmReconciliation = supplierSettlementConfirmDto.getIsConfirmReconciliation();


        // 通过ID查询供应商结算单，确保未被删除
        BamuSpReconciliationSettlement spReconciliationSettlement =
                iBamuSpReconciliationSettlementService.getByIdAndDeleted(id);
        // 如果结算单不存在，则返回错误结果
        if (Objects.isNull(spReconciliationSettlement)) {
            return YResult.error(ResultMsgEnum.NO_DATA);
        }
        // 获取结算单状态
        Integer status = spReconciliationSettlement.getStatus();
        // 如果状态不是“供应商已确认”，则返回错误结果
        if (status != ProjectSettlementStatusEnum.CONFIRMED_BY_SUPPLIER.getType()) {
            return YResult.error(ResultMsgEnum.RECONCILIATION_SETTLEMENT_STAY_CONFIRMED);
        }
        int reconciliationSettlementStatus = isConfirmReconciliation ?
                ProjectSettlementStatusEnum.CONFIRMED_BY_CLOUD_ACQUISITION.getType() :
                ProjectSettlementStatusEnum.SUPPLIER_CONFIRMATION_REJECTION.getType();
        // 更新结算单状态为“云采购已确认”
        spReconciliationSettlement.setStatus(reconciliationSettlementStatus);
        // 更新确认对账文件路径
        spReconciliationSettlement.setConfirmReconciliationSettlementFile(confirmReconciliationFile);
        // 更新确认对账备注
        spReconciliationSettlement.setConfirmReconciliationMark(confirmReconciliationMark);
        // 保存更新后的结算单信息
        iBamuSpReconciliationSettlementService.updateById(spReconciliationSettlement);
        // 获取当前用户信息
        UserInfoRequest userInfo = BaseContext.getUserInfo();
        // 插入审核确认历史记录
        iBamuAuditConfirmHistoryService.insertRecord(spReconciliationSettlement.getId(), new Date()
                , spReconciliationSettlement.getReconciliationPrice(),
                confirmReconciliationFile,
                confirmReconciliationMark,
                reconciliationSettlementStatus, "1",
                userInfo.getRealName());
        // 返回成功结果，包含结算单ID
        return YResult.success(spReconciliationSettlement.getId());
    }

    @Override
    public YResult<PageResult<SupplierSettlementOrderVO>> orderPageList(SupplierSettlementOrderDto supplierSettlementOrderDto) {
        LambdaQueryWrapper<BamuSpReconciliationSettlementOrder> queryWrapper =
                new LambdaQueryWrapper<BamuSpReconciliationSettlementOrder>()
                        .eq(BamuSpReconciliationSettlementOrder::getIsDeleted,
                                DataDeletedStatus.NO.getType())
                        .eq(BamuSpReconciliationSettlementOrder::getReconciliationSettlementId,
                                supplierSettlementOrderDto.getReconciliationSettlementId()).orderByAsc(BamuSpReconciliationSettlementOrder::getId);
        // 分页查询
        IPage<BamuSpReconciliationSettlementOrder> settlementPage =
                new Page<>(supplierSettlementOrderDto.getPageIndex(),
                        supplierSettlementOrderDto.getPageSize());
        settlementPage = iBamuSpReconciliationSettlementOrderService.page(settlementPage,
                queryWrapper);

        // 处理查询结果
        if (CollectionUtils.isEmpty(settlementPage.getRecords())) {
            return YResult.success(new PageResult<>());
        }

        // 转换为VO对象列表
        List<SupplierSettlementOrderVO> voList = orderDaoToVoList(settlementPage.getRecords());

        // 返回分页结果
        return YResult.success(new PageResult<>(voList, settlementPage.getCurrent(),
                settlementPage.getSize(), settlementPage.getPages(), settlementPage.getTotal()));
    }

    /**
     * 供应商-获取结算历史金额
     *
     * @param contractId
     * @return
     */
    @Override
    public BigDecimal getSupplyTaxTotalPrice(String contractId) {
        List<BamuSpReconciliationSettlementOrder> list = iBamuSpReconciliationSettlementOrderService.lambdaQuery()
                .eq(BamuSpReconciliationSettlementOrder::getContractId, contractId)
                .eq(BamuSpReconciliationSettlementOrder::getIsDeleted, DataDeletedStatus.NO.getType())
                .eq(BamuSpReconciliationSettlementOrder::getStatus, ReconciliationStatusEnum.CLOUD_ACQUISITION_CONFIRMATION_COMPLETE)
                .list();
        if (CollectionUtils.isEmpty(list)) {
            return BigDecimal.ZERO;
        }
        return list
                .stream()
                .map(BamuSpReconciliationSettlementOrder::getReconciliationPrice)
                .reduce(BigDecimal::add)
                .orElse(BigDecimal.ZERO);
    }


    private List<SupplierSettlementOrderVO> orderDaoToVoList(List<BamuSpReconciliationSettlementOrder> records) {
        return records.stream().map(this::orderDaoToVo).collect(Collectors.toList());
    }

    private SupplierSettlementOrderVO orderDaoToVo(BamuSpReconciliationSettlementOrder bamuSpReconciliationSettlementOrder) {
        SupplierSettlementOrderVO supplierSettlementOrderVO = new SupplierSettlementOrderVO();
        BeanUtils.copyProperties(bamuSpReconciliationSettlementOrder, supplierSettlementOrderVO);
        return supplierSettlementOrderVO;
    }

    /**
     * 保存供应商结算信息
     *
     * @param saveDto 供应商结算保存数据传输对象，包含所有的结算信息
     * @return 返回保存结果，包括生成的结算ID
     */
    @Override
    public YResult<String> save(SupplierSettlementSaveDto saveDto) {
        checkSaveData(saveDto);
        // 初始化结算实体对象
        BamuSpReconciliationSettlement settlement = new BamuSpReconciliationSettlement();
        settlement.setId(saveDto.getId());
        String contractId = saveDto.getContractId();
        saveSaleContractInfo(contractId, settlement);
        settlement.setStatus(0);
        // 解析并设置对账开始日期
        settlement.setReconciliationStartDate(DateUtils.parseDate(saveDto.getReconciliationStartDate(), DateFormatPattern.YEAR_MONTH_DAY.getPattern()));
        // 解析并设置对账结束日期
        settlement.setReconciliationEndDate(DateUtils.parseDate(saveDto.getReconciliationEndDate(),
                DateFormatPattern.YEAR_MONTH_DAY.getPattern()));
        // 解析并设置结算日期
        settlement.setSettlementDate(DateUtils.parseDate(saveDto.getSettlementDate(),
                DateFormatPattern.YEAR_MONTH_DAY.getPattern()));
        settlement.setContractMethod(saveDto.getContractMethod());
        settlement.setOrderNo(saveDto.getOrderNo());
        settlement.setOrderId(saveDto.getOrderId());
        if (saveDto.getId() == null) {
            settlement.setHistorySettlementAmount(getSupplyTaxTotalPrice(saveDto.getContractId()));
        } else {
            settlement.setHistorySettlementAmount(saveDto.getHistorySettlementAmount());
        }
        // 保存或更新结算信息
        iBamuSpReconciliationSettlementService.saveOrUpdate(settlement);
        // 批量保存对账结算订单
        spReconciliationSettlementOrderBatch(saveDto.getReconciliationIdList(),
                settlement.getId());
        updateSupplyInfo(settlement.getId());

        SupplierSettlementPayNodeSaveDto supplierSettlementPayNodeSaveDto = new SupplierSettlementPayNodeSaveDto();
        UserInfoRequest userInfo = BaseContext.getUserInfo();
        if (saveDto.getPayNodeIdList().size() > 0) {
            for (SupplierSettlementPayNodeSaveDto payNode : saveDto.getPayNodeIdList()) {
                supplierSettlementPayNodeSaveDto.setPaymentNode(payNode.getPaymentNode());
                Integer paidRatio = Integer.valueOf(payNode.getPaidRatio().replace("%", ""));
                Integer thispaidRatio = Integer.valueOf(payNode.getThisPaidRatio().replace("%", ""));
                Integer paymentRatio = paidRatio + thispaidRatio;
                supplierSettlementPayNodeSaveDto.setId(payNode.getId());
                supplierSettlementPayNodeSaveDto.setThisPaidRatio(thispaidRatio + "%");
                supplierSettlementPayNodeSaveDto.setPaidRatio(payNode.getPaidRatio() + "%");
                supplierSettlementPayNodeSaveDto.setPaymentRatio(paymentRatio + "%");
                supplierSettlementPayNodeSaveDto.setSettlementId(settlement.getId());
                supplierSettlementPayNodeSaveDto.setContractId(settlement.getContractId());
                supplierSettlementPayNodeSaveDto.setCreatedAt(new Date());
                supplierSettlementPayNodeSaveDto.setCreatedBy(userInfo.getRealName());
                supplierSettlementPayNodeSaveDto.setContractMethod(settlement.getContractMethod());
                supplierSettlementPayNodeSaveDto.setOrderId(saveDto.getOrderId());
//        supplierSettlementPayNodeSaveDto.setOrderId(settlement.getProjectId());
                supplierSettlementPayNodeSaveDto.setIsDeleted(0);
                iBamuSupplierSettlementPayNodeService.saveInfo(supplierSettlementPayNodeSaveDto);
            }
        }

        // 返回成功结果，包含结算ID
        return YResult.success(settlement.getId());
    }

    private void updateSupplyInfo(String id) {
        BamuSpReconciliationSettlement settlement = new BamuSpReconciliationSettlement();
        settlement.setId(id);
        List<BamuSpReconciliationSettlementOrder> spReconciliationSettlementOrderList =
                iBamuSpReconciliationSettlementOrderService.listByReconciliationSettlementIdDeleted(id);
        if (CollectionUtils.isEmpty(spReconciliationSettlementOrderList)) {
            return;
        }
        int supplyNum =
                spReconciliationSettlementOrderList.stream().map(BamuSpReconciliationSettlementOrder::getSupplyNum).mapToInt(Integer::intValue).sum();
        double supplyIncludingTaxTotalPrice =
                spReconciliationSettlementOrderList.stream().map(BamuSpReconciliationSettlementOrder::getSupplyIncludingTaxTotalPrice).mapToDouble(BigDecimal::doubleValue).sum();
        double reconciliationPrice =
                spReconciliationSettlementOrderList.stream().map(BamuSpReconciliationSettlementOrder::getReconciliationPrice).mapToDouble(BigDecimal::doubleValue).sum();
        settlement.setSupplyNum(supplyNum);
        settlement.setSupplyIncludingTaxTotalPrice(BigDecimal.valueOf(supplyIncludingTaxTotalPrice));
        settlement.setSettlementNum(spReconciliationSettlementOrderList.size());
        settlement.setReconciliationPrice(BigDecimal.valueOf(reconciliationPrice));
        iBamuSpReconciliationSettlementService.updateById(settlement);
    }

    private void saveSaleContractInfo(String contractId,
                                      BamuSpReconciliationSettlement settlement) {
        BamuPurchaseContract purchaseContract = iBamuPurchaseContractService.getByIdNoDelete(contractId);
        if (Objects.isNull(purchaseContract)) {
            return;
        }
        settlement.setContractId(contractId);
        settlement.setContractNo(purchaseContract.getContractNo());
        settlement.setContractName(purchaseContract.getContractName());
        settlement.setPurchaseDeptId(purchaseContract.getPurchaseDeptId());
        settlement.setPurchaseDeptName(purchaseContract.getPurchaseDeptName());
        settlement.setPurchaseDeptName(purchaseContract.getPurchaseDeptName());
        settlement.setProjectId(purchaseContract.getProjectId());
        settlement.setProjectName(purchaseContract.getProjectName());
        settlement.setSupplyDeptId(purchaseContract.getSupplyDeptId());
        settlement.setSupplyDeptName(purchaseContract.getSupplyDeptName());
        settlement.setSupplierDeptId(purchaseContract.getSupplierDeptId());
        settlement.setSupplierDeptName(purchaseContract.getSupplierDeptName());
        settlement.setContractMethod(purchaseContract.getContractMethod());
        settlement.setProjectDeptId(purchaseContract.getProjectDeptId());
        settlement.setProjectDeptName(purchaseContract.getProjectDeptName());
        settlement.setContractRebatePoints(purchaseContract.getContractRebatePoints());
        BigDecimal contractRebatePoints = purchaseContract.getContractRebatePoints();
        BigDecimal contractTotalRealPrice = purchaseContract.getContractTotalRealPrice();
        if (Objects.nonNull(contractRebatePoints) && Objects.nonNull(contractTotalRealPrice)
                && contractRebatePoints.doubleValue() > BigDecimal.ZERO.doubleValue() && contractTotalRealPrice.doubleValue() > BigDecimal.ZERO.doubleValue()) {
            settlement.setContractRebatePrice(contractRebatePoints.divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP).multiply(contractTotalRealPrice));
        }

    }

    private void checkSaveData(SupplierSettlementSaveDto saveDto) {
        String contractId = saveDto.getContractId();
        if (StringUtils.isBlank(contractId)) {
            throw new BusinessException("合同参数必传");
        }
        BamuPurchaseContract bamuPurchaseContract = iBamuPurchaseContractService.getByIdNoDelete(contractId);
        if (Objects.isNull(bamuPurchaseContract)) {
            throw new BusinessException("未查询可用合同");
        }
        String settlementDate = saveDto.getSettlementDate();
        if (StringUtils.isBlank(settlementDate)) {
            throw new BusinessException("结算时间参数必传");
        }
        List<String> reconciliationIdList = saveDto.getReconciliationIdList();
        if (CollectionUtils.isEmpty(reconciliationIdList)) {
            throw new BusinessException("对账单参数必传");
        }
        List<String> distinctReconciliationIdList =
                reconciliationIdList.stream().distinct().toList();
        if (distinctReconciliationIdList.size() != reconciliationIdList.size()) {
            throw new BusinessException("对账单参数重复");
        }
    }


    @Override
    public YResult<String> submitApproval(SupplierSettlementSubmitApprovalDto submitApprovalDto) {
        try {
            // 调用处理类的submit方法，传入审批ID，执行审批提交操作
            supplierSettlementAuditHandle.submit(submitApprovalDto.getId());
            // 如果审批提交成功，返回成功结果，包含审批的ID
            return YResult.success(submitApprovalDto.getId());
        } catch (Exception e) {
            log.error("提交审批异常", e);
            // 如果审批提交过程中发生异常，返回错误结果，包含异常信息
            return YResult.error(ResultMsgEnum.SUBMIT_APPROVAL_ERROR);
        }
    }

    @Override
    public YResult<String> approval(SupplierSettlementApprovalDto approvalDto) {
        try {
            // 调用供应商结算审批处理类的approval方法进行审批操作
            supplierSettlementAuditHandle.approval(approvalDto);
            // 审批成功后，返回成功结果，携带审批后的ID
            return YResult.success(approvalDto.getId());
        } catch (Exception e) {
            log.error("审批供应商结算失败", e);
            // 审批过程中发生异常，返回错误结果，携带异常信息
            return YResult.error(ResultMsgEnum.APPROVAL_ERROR);
        }
    }

    @Override
    public YResult<String> check(SupplierSettlementCheckDto supplierSettlementCheckDto) {
        // 提取DTO中的主要字段
        String id = supplierSettlementCheckDto.getId();
        BigDecimal reconciliationPrice = supplierSettlementCheckDto.getReconciliationPrice();
        String checkFile = supplierSettlementCheckDto.getCheckFile();
        String checkMark = supplierSettlementCheckDto.getCheckMark();
        if (!ConvertUtil.isValidNotEmptyJson(checkFile)) {
            checkFile = "[]";
        }
        // 根据ID获取核对结算单据，确保它未被删除
        BamuSpReconciliationSettlement spReconciliationSettlement =
                iBamuSpReconciliationSettlementService.getByIdAndDeleted(id);
        if (Objects.isNull(spReconciliationSettlement)) {
            // 如果找不到结算单据，返回错误信息
            return YResult.error(ResultMsgEnum.NO_DATA);
        }

        // 检查结算单据的状态是否为“待核对”
        Integer status = spReconciliationSettlement.getStatus();
        if (status != ProjectSettlementStatusEnum.TO_BE_CHECKED.getType()) {
            // 如果不在“待核对”状态，返回错误信息
            return YResult.error(ResultMsgEnum.RECONCILIATION_SETTLEMENT_CHECK);
        }

        // 更新核对结算单据的信息，包括核对价格、核对文件、核对备注，并将其状态更改为“已核对”
        //reconciliationSettlement.setReconciliationPrice(reconciliationPrice);
        spReconciliationSettlement.setCheckFile(checkFile);
        spReconciliationSettlement.setCheckMark(checkMark);
        spReconciliationSettlement.setStatus(ProjectSettlementStatusEnum.CHECKED_OUT.getType());
        iBamuSpReconciliationSettlementService.updateById(spReconciliationSettlement);

        // 记录核对操作的历史记录
        UserInfoRequest userInfo = BaseContext.getUserInfo();
        iBamuAuditConfirmHistoryService.insertRecord(spReconciliationSettlement.getId(), new Date()
                , reconciliationPrice, checkFile, checkMark,
                ProjectSettlementStatusEnum.CHECKED_OUT.getType(), "0",
                userInfo.getRealName());

        // 返回成功结果，包含核对结算单据的ID
        return YResult.success(spReconciliationSettlement.getId());
    }

    @Override
    public YResult<String> deleted(SupplierSettlementDeletedDto supplierSettlementDeletedDto) {
        try {
            String id = supplierSettlementDeletedDto.getId();
            BamuSpReconciliationSettlement spReconciliationSettlement =
                    iBamuSpReconciliationSettlementService.getByIdAndDeleted(id);
            if (Objects.isNull(spReconciliationSettlement)) {
                // 如果找不到结算单据，返回错误信息
                return YResult.error(ResultMsgEnum.NO_DATA);
            }
            if (spReconciliationSettlement.getIsDeleted() == DataDeletedStatus.YES.getType()) {
                // 如果结算单据已经被删除，返回错误信息
                return YResult.error(ResultMsgEnum.DELETED_DELETED_DATA_ERROR);
            }
            spReconciliationSettlement.setIsDeleted(DataDeletedStatus.YES.getType());
            iBamuSpReconciliationSettlementService.updateById(spReconciliationSettlement);
            return YResult.success(id);
        } catch (Exception e) {
            log.error("删除供应商结算失败", e);
            // 如果删除失败，返回错误结果，携带异常信息
            return YResult.error(ResultMsgEnum.SYS_ERROR);
        }
    }

    @Override
    public YResult<String> ycConfirm(SupplierSettlementConfirmDto supplierSettlementConfirmDto) {
        // 提取供应商结算单ID
        String id = supplierSettlementConfirmDto.getId();
        // 提取确认对账文件路径
        String confirmReconciliationFile =
                supplierSettlementConfirmDto.getConfirmReconciliationFile();
        // 提取确认对账备注
        String confirmReconciliationMark =
                supplierSettlementConfirmDto.getConfirmReconciliationMark();
        // 获取当前用户信息
        UserInfoRequest userInfo = BaseContext.getUserInfo();

        // 通过ID查询供应商结算单，确保未被删除
        BamuSpReconciliationSettlement spReconciliationSettlement =
                iBamuSpReconciliationSettlementService.getByIdAndDeleted(id);
        // 如果结算单不存在，则返回错误结果
        if (Objects.isNull(spReconciliationSettlement)) {
            return YResult.error(ResultMsgEnum.NO_DATA);
        }
        // 获取结算单状态
        Integer status = spReconciliationSettlement.getStatus();
        // 如果状态不是“供应商已确认”，则返回错误结果
        if (status != ProjectSettlementStatusEnum.CONFIRMED_BY_CLOUD_ACQUISITION.getType()) {
            return YResult.error(ResultMsgEnum.RECONCILIATION_SETTLEMENT_STAY_YC_CONFIRMED);
        }
        // 更新结算单状态为“云采购已确认”
        spReconciliationSettlement.setStatus(ProjectSettlementStatusEnum.PAYMENT_TO_BE_COLLECTED.getType());
        // 更新确认对账文件路径
        if (ConvertUtil.isValidNotEmptyJson(confirmReconciliationFile)) {
            spReconciliationSettlement.setYcFile(confirmReconciliationFile);
        } else {
            spReconciliationSettlement.setYcFile("[]");
        }

        // 更新确认对账备注
        spReconciliationSettlement.setYcConfirmMark(confirmReconciliationMark);
        // 保存更新后的结算单信息
        iBamuSpReconciliationSettlementService.updateById(spReconciliationSettlement);
        updateSpReconciliationSuccessStatus(id);
        // 插入审核确认历史记录
        iBamuAuditConfirmHistoryService.insertRecord(spReconciliationSettlement.getId(), new Date()
                , spReconciliationSettlement.getReconciliationPrice(),
                confirmReconciliationFile,
                confirmReconciliationMark,
                ProjectSettlementStatusEnum.PAYMENT_TO_BE_COLLECTED.getType(), "3",
                userInfo.getRealName());
        // 返回成功结果，包含结算单ID
        return YResult.success(spReconciliationSettlement.getId());
    }

    private void updateSpReconciliationSuccessStatus(String id) {
        List<BamuSpReconciliationSettlementOrder> spReconciliationSettlementOrderList =
                iBamuSpReconciliationSettlementOrderService.listByReconciliationSettlementIdDeleted(id);
        if (CollectionUtils.isEmpty(spReconciliationSettlementOrderList)) {
            return;
        }
        for (BamuSpReconciliationSettlementOrder bamuSpReconciliationSettlementOrder :
                spReconciliationSettlementOrderList) {
            String reconciliationId = bamuSpReconciliationSettlementOrder.getReconciliationId();
            BamuSpReconciliation bamuSpReconciliation =
                    iBamuSpReconciliationService.getByIdNoDelete(reconciliationId);
            if (Objects.isNull(bamuSpReconciliation)) {
                return;
            }
            Integer status = bamuSpReconciliation.getStatus();
            if (Objects.equals(status, ReconciliationStatusEnum.PAYMENT_COLLECTION_IN_PROGRESS.getType())) {
                bamuSpReconciliation.setStatus(ReconciliationStatusEnum.PAYMENT_COLLECTION_COMPLETE.getType());
                iBamuSpReconciliationService.updateById(bamuSpReconciliation);
            }
        }
    }

    @Override
    public YResult<Map<String, Object>> materialCount(SupplierSettlementMaterialDto supplierSettlementMaterialDto) {
        String reconciliationSettlementId =
                supplierSettlementMaterialDto.getReconciliationSettlementId();
        Map<String, Object> map =
                iBamuSpReconciliationSettlementOrderMaterialService.getMaterialSumMap(reconciliationSettlementId);
        return YResult.success(map);
    }

    /**
     * 批量保存对账结算单
     * <p>
     * 此方法主要用于处理一批对账ID的结算单保存逻辑如果给定的对账ID列表为空，则不执行任何操作
     * 如果根据对账ID列表查找到的结算单为空，则会尝试批量保存新的结算单信息
     *
     * @param reconciliationIdList       对账ID列表，用于查询或保存结算单
     * @param reconciliationSettlementId 结算单ID，用于关联结算单和对账单
     */
    private void spReconciliationSettlementOrderBatch(List<String> reconciliationIdList,
                                                      String reconciliationSettlementId) {
        // 检查对账ID列表是否为空，为空则直接返回
        if (CollectionUtils.isEmpty(reconciliationIdList)) {
            throw new BusinessException("对账单参数必传");
        }
        // 根据对账单ID列表查询已删除的对账单信息
        List<BamuSpReconciliation> bamuSpReconciliationList =
                iBamuSpReconciliationService.listByIdsDeleted(reconciliationIdList);
        if (CollectionUtils.isEmpty(bamuSpReconciliationList)) {
            throw new BusinessException("对账单信息异常");
        }
        // 根据对账ID列表查询已删除的结算单列表
        List<BamuSpReconciliationSettlementOrder> spReconciliationSettlementOrderList =
                iBamuSpReconciliationSettlementOrderService.listByReconciliationSettlementIdDeleted(reconciliationSettlementId);
        List<String> oldReconciliationIdList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(spReconciliationSettlementOrderList)) {
            List<String> deleteIdList =
                    spReconciliationSettlementOrderList.stream().map(BamuSpReconciliationSettlementOrder::getReconciliationId)
                            .filter(reconciliationId -> !reconciliationIdList.contains(reconciliationId)).toList();
            if (CollectionUtils.isNotEmpty(deleteIdList)) {
                iBamuSpReconciliationSettlementOrderService.deletedByReconciliationIdList(deleteIdList);
                iBamuSpReconciliationSettlementOrderMaterialService.deletedByReconciliationIdList(deleteIdList);
                iBamuSpReconciliationService.unBindSettlement(deleteIdList);
            }
            oldReconciliationIdList =
                    spReconciliationSettlementOrderList.stream().map(BamuSpReconciliationSettlementOrder::getReconciliationId).toList();
        }
        List<String> finalOldReconciliationIdList = oldReconciliationIdList;
        List<String> filterReconciliationIdList =
                reconciliationIdList.stream().filter(x -> !finalOldReconciliationIdList.contains(x)).toList();
        if (CollectionUtils.isEmpty(filterReconciliationIdList)) {
            return;
        }
        List<BamuSpReconciliation> reconciliationList =
                bamuSpReconciliationList.stream().filter(x -> filterReconciliationIdList.contains(x.getId())).toList();
        // 批量保存对账单与结算单的关联关系
        reconciliationSettlementSaveBatch(reconciliationList, reconciliationSettlementId, filterReconciliationIdList);
    }


    /**
     * 批量保存对账结算信息
     * 该方法主要用于将对账单与结算单关联，并保存相关联的明细信息
     *
     * @param spReconciliationList       对账单ID列表，用于查询对应的对账单信息
     * @param reconciliationSettlementId 结算单ID，用于关联对账单与结算单
     * @param filterReconciliationIdList
     */
    private void reconciliationSettlementSaveBatch(List<BamuSpReconciliation> spReconciliationList,
                                                   String reconciliationSettlementId, List<String> filterReconciliationIdList) {
        // 将对账单信息转换为对账结算单信息列表
        List<BamuSpReconciliationSettlementOrder> spReconciliationSettlementOrderList =
                spReconciliationList.stream().map(x -> reconciliationToSettlementOrder(x,
                        reconciliationSettlementId)).collect(Collectors.toList());
        // 批量保存对账结算单信息
        iBamuSpReconciliationSettlementOrderService.saveBatch(spReconciliationSettlementOrderList);
        iBamuSpReconciliationService.bindSettlement(filterReconciliationIdList);
        // 遍历对账结算单信息列表，处理每张对账单的明细信息
        for (BamuSpReconciliationSettlementOrder bamuSpReconciliationSettlementOrder :
                spReconciliationSettlementOrderList) {
            // 获取当前对账结算单的唯一标识
            String id = bamuSpReconciliationSettlementOrder.getId();
            // 获取当前对账结算单关联的对账单ID
            String reconciliationId = bamuSpReconciliationSettlementOrder.getReconciliationId();
            // 根据对账单ID查询对应的对账明细信息
            List<BamuSpReconciliationOrderMaterial> spReconciliationOrderMaterialList =
                    iBamuSpReconciliationOrderMaterialService.listByReconciliationId(reconciliationId);
            // 如果对账明细信息列表不为空，则进行处理
            if (CollectionUtils.isNotEmpty(spReconciliationOrderMaterialList)) {
                // 将对账明细信息转换为对账结算明细信息列表
                List<BamuSpReconciliationSettlementOrderMaterial> bamuSpReconciliationSettlementOrderMaterialList =
                        spReconciliationOrderMaterialList.stream().map(x -> reconciliationToSettlementOrderMaterial(x, reconciliationSettlementId, id)).toList();
                // 批量保存对账结算明细信息
                iBamuSpReconciliationSettlementOrderMaterialService.saveBatch(bamuSpReconciliationSettlementOrderMaterialList);
            }
        }
    }


    /**
     * 将对账单材料转换为结算单材料对象
     * <p>
     * 此方法主要用于在对账单材料和结算单材料之间进行转换，以便在结算过程中使用对账单材料的信息
     * 它复制了对账单材料的属性，并为结算单材料设置了特定的结算单ID和结算单项ID
     *
     * @param bamuSpReconciliationOrderMaterial 对账单材料对象，其属性将被复制到结算单材料对象中
     * @param reconciliationSettlementId        结算单的唯一标识符，将被设置到结算单材料对象中
     * @param reconciliationSettlementOrderId   结算单项的唯一标识符，将被设置到结算单材料对象中
     * @return 返回一个新的结算单材料对象，其属性基于输入的对账单材料，但带有新的结算单ID和结算单项ID
     */
    private BamuSpReconciliationSettlementOrderMaterial reconciliationToSettlementOrderMaterial(BamuSpReconciliationOrderMaterial bamuSpReconciliationOrderMaterial,
                                                                                                String reconciliationSettlementId,
                                                                                                String reconciliationSettlementOrderId) {
        // 初始化一个新的结算单材料对象
        BamuSpReconciliationSettlementOrderMaterial spReconciliationSettlementOrderMaterial =
                new BamuSpReconciliationSettlementOrderMaterial();
        // 复制对账单材料对象的属性到结算单材料对象
        BeanUtils.copyProperties(bamuSpReconciliationOrderMaterial,
                spReconciliationSettlementOrderMaterial);
        // 设置结算单ID
        spReconciliationSettlementOrderMaterial.setReconciliationSettlementId(reconciliationSettlementId);
        // 设置结算单项ID
        spReconciliationSettlementOrderMaterial.setReconciliationSettlementOrderId(reconciliationSettlementOrderId);
        // 为新生成的结算单材料对象设置一个空的ID，表示它是一个新对象
        spReconciliationSettlementOrderMaterial.setId(null);
        // 返回新的结算单材料对象
        return spReconciliationSettlementOrderMaterial;
    }

    /**
     * 将对账结果转换为结算单
     * <p>
     * 此方法接收一个对账结果对象和一个结算单ID作为参数，将对账结果转换为结算单对象
     * 转换过程中，会复制对账结果的属性到结算单对象中，并设置结算单的唯一ID，
     * 同时保留原对账单的ID，并将结算单对象的ID设置为null，以标记这是一个新的结算单记录
     *
     * @param bamuSpReconciliation       对账结果对象，包含需要转换为结算单的对账信息
     * @param reconciliationSettlementId 结算单的唯一标识符
     * @return 返回转换后的结算单对象
     */
    private BamuSpReconciliationSettlementOrder reconciliationToSettlementOrder(BamuSpReconciliation bamuSpReconciliation, String reconciliationSettlementId) {
        // 初始化一个新的结算单对象
        BamuSpReconciliationSettlementOrder spReconciliationSettlementOrder =
                new BamuSpReconciliationSettlementOrder();
        // 复制对账结果的属性到结算单对象
        BeanUtils.copyProperties(bamuSpReconciliation, spReconciliationSettlementOrder);
        // 设置结算单的唯一ID
        spReconciliationSettlementOrder.setReconciliationSettlementId(reconciliationSettlementId);
        // 保留原对账单的ID
        spReconciliationSettlementOrder.setReconciliationId(bamuSpReconciliation.getId());
        // 将结算单对象的ID设置为null，标记这是一个新的记录
        spReconciliationSettlementOrder.setId(null);
        // 返回转换后的结算单对象
        return spReconciliationSettlementOrder;
    }


    @Override
    public List<SettlementExcelDto> export(SupplierSettlementDto supplierSettlementDto) {
        // 构建查询条件
        LambdaQueryWrapper<BamuSpReconciliationSettlement> queryWrapper =
                new LambdaQueryWrapper<BamuSpReconciliationSettlement>()
                        .like(StringUtils.isNotBlank(supplierSettlementDto.getContractNo()), BamuSpReconciliationSettlement::getContractNo, supplierSettlementDto.getContractNo())
                        .eq(BamuSpReconciliationSettlement::getIsDeleted,
                                DataDeletedStatus.NO.getType())
                        .between(StringUtils.isNotBlank(supplierSettlementDto.getSettlementStartDate()) && StringUtils.isNotBlank(supplierSettlementDto.getSettlementEndDate()),
                                BamuSpReconciliationSettlement::getSettlementDate,
                                ConvertUtil.getStartOfDay(ConvertUtil.getString2Date(supplierSettlementDto.getSettlementStartDate())),
                                ConvertUtil.getEndOfDay(ConvertUtil.getString2Date(supplierSettlementDto.getSettlementEndDate())))
                        .eq(StringUtils.isNotBlank(supplierSettlementDto.getContractId()),
                                BamuSpReconciliationSettlement::getContractId,
                                supplierSettlementDto.getContractId())
                        .eq(StringUtils.isNotBlank(supplierSettlementDto.getContractMethod()),
                                BamuSpReconciliationSettlement::getContractMethod,
                                supplierSettlementDto.getContractMethod())
                        .like(StringUtils.isNotBlank(supplierSettlementDto.getContractName()),
                                BamuSpReconciliationSettlement::getContractName,
                                supplierSettlementDto.getContractName())
                        .eq(StringUtils.isNotBlank(supplierSettlementDto.getProjectId()),
                                BamuSpReconciliationSettlement::getProjectId,
                                supplierSettlementDto.getProjectId())
                        .like(StringUtils.isNotBlank(supplierSettlementDto.getProjectName()),
                                BamuSpReconciliationSettlement::getProjectName,
                                supplierSettlementDto.getProjectName())
                        .like(StringUtils.isNotBlank(supplierSettlementDto.getSupplierDeptName()),
                                BamuSpReconciliationSettlement::getSupplierDeptName,
                                supplierSettlementDto.getSupplierDeptName())
                        .in(CollectionUtils.isNotEmpty(BaseContext.getProjectList()), BamuSpReconciliationSettlement::getProjectId, BaseContext.getProjectList())
                        .in(CollectionUtils.isNotEmpty(BaseContext.getSupplierList()),
                                BamuSpReconciliationSettlement::getSupplierDeptId,
                                BaseContext.getSupplierList()).orderByDesc(BamuSpReconciliationSettlement::getId);
        List<BamuSpReconciliationSettlement> contractMaterialList = iBamuSpReconciliationSettlementService.list(queryWrapper);
        if (CollectionUtils.isNotEmpty(contractMaterialList)) {
            return contractMaterialList.stream().map(this::convertToExcelDto).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }

    /**
     * 将BamuContractMaterial转化成ContractMaterialExportDto
     */
    private SettlementExcelDto convertToExcelDto(BamuSpReconciliationSettlement bamuPurchaseApply) {
        SettlementExcelDto dto = new SettlementExcelDto();
        BeanUtils.copyProperties(bamuPurchaseApply, dto);
        dto.setId(bamuPurchaseApply.getId());
        return dto;
    }
}
